<template>
  <view class="digest-detail">
    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <uni-load-more status="loading" />
    </view>

    <!-- 文章内容 -->
    <view class="article-container" v-else-if="digestData">
      <!-- 文章头部 -->
      <view class="article-header">
        <view class="title">{{ digestData.generatedTitle || '无标题' }}</view>
        <view class="meta-info">
          <view class="meta-item">
            <text class="meta-label">作者：</text>
            <text class="meta-value">{{ digestData.createdBy || '系统' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">发布时间：</text>
            <text class="meta-value">{{ formatTime(digestData.createdTime) }}</text>
          </view>

        </view>
      </view>



      <!-- 文章摘要 -->
      <view class="summary-section" v-if="digestData.summaryContent">
        <view class="section-title">文章摘要</view>
        <view class="summary-content">
          {{ digestData.summaryContent }}
        </view>
      </view>

      <!-- 文章正文 -->
      <view class="content-section" v-if="digestData.generatedArticle">
        <view class="section-title">正文内容</view>
        <view class="article-content">
          <rich-text :nodes="formatContent(digestData.generatedArticle)"></rich-text>
        </view>
      </view>



      <!-- 操作按钮 -->
      <view class="action-section">
        <button class="action-btn primary" @click="handleGoToQuestion">
          <uni-icons type="redo" size="18" color="#fff"></uni-icons>
          <text>答题</text>
        </button>
        <button class="action-btn secondary" @click="handleCollect">
          <uni-icons type="star" size="18" color="#007AFF"></uni-icons>
          <text>收藏</text>
        </button>
      </view>
    </view>

    <!-- 错误状态 -->
    <view class="error-container" v-else>
      <view class="error-content">
        <uni-icons type="info" size="60" color="#ccc"></uni-icons>
        <text class="error-text">{{ errorMessage || '文章不存在或已被删除' }}</text>
        <button class="retry-btn" @click="fetchDigestDetail">重试</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getDigest, type DigestDetail } from '@/api/digest/digest'

// 使用从 API 文件导入的类型定义

// 响应式数据
const loading = ref(false)
const digestData = ref<DigestDetail | null>(null)
const digestId = ref<string>('')
const errorMessage = ref<string>('')

// 计算属性移除（不再需要关键词）

// 格式化时间
const formatTime = (timeStr: string) => {
  if (!timeStr) return '未知'
  try {
    const date = new Date(timeStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return timeStr
  }
}

// 格式化文章内容
const formatContent = (content: string) => {
  if (!content) return ''

  // 简单的文本格式化，将换行转换为<br>
  return content
      .replace(/\n/g, '<br/>')
      .replace(/\s{2,}/g, '&nbsp;&nbsp;') // 多个空格转换为不间断空格
}

// 获取文章详情
const fetchDigestDetail = async () => {
  if (!digestId.value) {
    errorMessage.value = '缺少文章ID参数'
    return
  }

  loading.value = true
  errorMessage.value = ''

  try {
    console.log('Calling getDigest with id:', digestId.value)
    console.log('getDigest function:', getDigest)
    const res = await getDigest(digestId.value)

    if (res && res.code === 200) {
      if (res.data) {
        digestData.value = res.data
      } else {
        errorMessage.value = '文章数据为空'
      }
    } else {
      errorMessage.value = res.msg || '获取文章详情失败'
    }
  } catch (error) {
    console.error('获取文章详情失败：', error)
    errorMessage.value = '网络请求失败，请检查网络连接'
  } finally {
    loading.value = false
  }
}

// 前往答题页面
const handleGoToQuestion = () => {
  if (!digestData.value?.id) {
    uni.showToast({
      title: '文章ID不存在',
      icon: 'none'
    })
    return
  }

  uni.navigateTo({
    url: `/pages/question/index?articleId=${digestData.value.id}`
  })
}

// 收藏功能
const handleCollect = () => {
  // 这里可以调用收藏API
  uni.showToast({
    title: '收藏成功',
    icon: 'success'
  })
}

// 页面加载时获取参数
onLoad((options) => {
  if (options?.id) {
    digestId.value = options.id
  } else {
    errorMessage.value = '缺少文章ID参数'
  }
})

// 组件挂载时获取数据
onMounted(() => {
  if (digestId.value) {
    fetchDigestDetail()
  }
})

// 设置导航栏标题
uni.setNavigationBarTitle({
  title: '热点文章详情'
})
</script>

<style lang="scss" scoped>
.digest-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
}

.article-container {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.article-header {
  padding: 40rpx 30rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;

  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    line-height: 1.4;
    margin-bottom: 24rpx;
  }

  .meta-info {
    .meta-item {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;
      font-size: 26rpx;

      .meta-label {
        color: #999;
        margin-right: 8rpx;
      }

      .meta-value {
        color: #666;
      }
    }
  }
}


.summary-section,
.content-section {

  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    position: relative;
    padding-left: 20rpx;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6rpx;
      height: 32rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 3rpx;
    }
  }
}



.summary-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  background-color: #f8f9fa;
  padding: 24rpx;
  border-radius: 12rpx;
  border-left: 4rpx solid #007AFF;
}

.article-content {
  font-size: 30rpx;
  color: #333;
  line-height: 1.8;
  text-align: justify;
}



.action-section {
  padding: 30rpx;
  display: flex;
  gap: 20rpx;

  .action-btn {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12rpx;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    border: none;

    &.primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #fff;
    }

    &.secondary {
      background-color: #f8f9fa;
      color: #007AFF;
      border: 1px solid #007AFF;
    }
  }
}

.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60vh;

  .error-content {
    text-align: center;

    .error-text {
      display: block;
      font-size: 28rpx;
      color: #999;
      margin: 30rpx 0;
    }

    .retry-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #fff;
      border: none;
      padding: 16rpx 40rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
    }
  }
}
</style>
